package com.haochang.chunkvod.controller.activity.order;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.haochang.base.BaseActivity;
import com.haochang.base.BaseListView;
import com.haochang.base.BaseTextView;
import com.haochang.base.OnBaseClickListener;
import com.haochang.chunkvod.R;
import com.haochang.chunkvod.app.common.VodConstant;
import com.haochang.chunkvod.app.common.intent.IntentCode;
import com.haochang.chunkvod.app.common.intent.IntentKey;
import com.haochang.chunkvod.app.utils.CollectionUtils;
import com.haochang.chunkvod.app.utils.SaleUtils;
import com.haochang.chunkvod.app.utils.TimeUtils;
import com.haochang.chunkvod.app.utils.ToastUtils;
import com.haochang.chunkvod.app.utils.VodDialog;
import com.haochang.chunkvod.controller.adapter.base.BaseAdapterHelper;
import com.haochang.chunkvod.controller.adapter.base.QuickAdapter;
import com.haochang.chunkvod.model.order.FoodDetailInfo;
import com.haochang.chunkvod.model.order.GoodsInfo;
import com.haochang.chunkvod.model.order.WeChatInfo;
import com.haochang.chunkvod.model.order.WeChatOrderData;
import com.haochang.chunkvod.tools.vod.goods.ShoppingCartManager;
import com.haochang.chunkvod.tools.vod.log.Logger;
import com.haochang.chunkvod.tools.vod.other.DipPxConversion;
import com.haochang.chunkvod.view.vod.activity.ActivityDialogEnum;
import com.haochang.chunkvod.view.vod.activity.WeChatOrderDialogActivity;
import com.haochang.chunkvod.view.vod.title.TitleView;

import android.content.Intent;
import android.content.res.ColorStateList;
import android.os.Bundle;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.TextAppearanceSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;

/**
 * @author qintao
 *         created at 2016/6/12 12:09
 *         微信点餐确认
 */

public class OrderWeChatDetailActivity extends BaseActivity
{
	private TitleView titleView;
	private BaseListView listView;
	private QuickAdapter dataAdapter;
	private Button btn_sure;
	private Button btn_cancel;
	private BaseTextView tv_cashTotal;
	private String roomNum;
	private String billId;
	private List<WeChatInfo> weChatInfoList = new ArrayList<WeChatInfo>();
	private WeChatOrderData weChatOrderData;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
	}

	@Override
	public void receiveParam()
	{
		roomNum = getIntent().getStringExtra(IntentKey.ROOM_NUM);
		billId = getIntent().getStringExtra(IntentKey.BILL_ID);
	}

	@Override
	public void initData()
	{
		weChatOrderData = new WeChatOrderData(OrderWeChatDetailActivity.this);
	}

	@Override
	public void initViews()
	{
		setContentView(R.layout.activity_order_we_chat);
		titleView = (TitleView) findViewById(R.id.titleView);
		titleView.setTitle(String.format("微信点餐确认(%s)", roomNum)).setRightIconVISIBLE(false).setTitleOnClickListener(new TitleView.ITitleOnClickListener()
		{
			@Override
			public void onBackClick()
			{
				finish();
			}

			@Override
			public void onDoneClick()
			{

			}
		});
		listView = (BaseListView) findViewById(R.id.listView);
		dataAdapter = new QuickAdapter<WeChatInfo>(OrderWeChatDetailActivity.this, R.layout.item_we_chat_order_detail_list_layout, weChatInfoList)
		{

			@Override
			protected void convert(BaseAdapterHelper helper, WeChatInfo item)
			{
				convertData(helper, item);
			}

		};
		listView.setVisibility(View.VISIBLE);
		listView.setAdapter(dataAdapter);
		btn_sure = (Button) findViewById(R.id.btn_sure);
		btn_cancel = (Button) findViewById(R.id.btn_cancel);
		btn_sure.setOnClickListener(onBaseClickListener);
		btn_cancel.setOnClickListener(onBaseClickListener);
		tv_cashTotal = (BaseTextView) findViewById(R.id.tv_cashTotal);
		weChatOrderData.requestWeChatOrderDetail(billId, new WeChatOrderData.IWeChatOrderDetailListener()
		{
			@Override
			public void onRequestSuccess(int cashTotal, List<WeChatInfo> list)
			{
				if (!CollectionUtils.isEmpty(list))
				{
					tv_cashTotal.setText(SaleUtils.getSaleString(cashTotal));
					weChatInfoList.clear();
					weChatInfoList.addAll(list);
					dataAdapter.replaceAll(weChatInfoList);
				}
			}
		});
	}

	private void convertData(final BaseAdapterHelper helper, final WeChatInfo item)
	{
		helper.setText(R.id.tv_nickName, item.getNickName());
		helper.setText(R.id.tv_payTime, TimeUtils.getMinutesString(item.getOrderTime()));
		final LinearLayout center_div = helper.getView(R.id.lay_center_div);
		center_div.removeAllViews();
		List<GoodsInfo> goodsInfoList = item.getGoodsInfoList();
		for (int i = 0; i < goodsInfoList.size(); i++)
		{
			final GoodsInfo info = goodsInfoList.get(i);
			final LinearLayout viewItem = (LinearLayout) LayoutInflater.from(context).inflate(R.layout.item_we_chat_order_center_layout, null);
			BaseTextView tv_foodName = (BaseTextView) viewItem.findViewById(R.id.tv_foodName);
			final BaseTextView tv_num = (BaseTextView) viewItem.findViewById(R.id.tv_num);
			BaseTextView tv_totalPrice = (BaseTextView) viewItem.findViewById(R.id.tv_totalPrice);
			BaseTextView tv_unit = (BaseTextView) viewItem.findViewById(R.id.tv_unit);
			ImageView img_del = (ImageView) viewItem.findViewById(R.id.img_del);
			ImageView iv_direction = (ImageView) viewItem.findViewById(R.id.iv_direction);
			BaseTextView tv_flavor_info = (BaseTextView) viewItem.findViewById(R.id.tv_flavor_info);
			LinearLayout lay_content_div = (LinearLayout) viewItem.findViewById(R.id.lay_content_div);
			//			View v_line = viewItem.findViewById(R.id.v_line);
			//			if (i == 0)
			//				v_line.setVisibility(View.INVISIBLE);
			//			else
			//				v_line.setVisibility(View.VISIBLE);
			tv_foodName.setText(info.getGoodsName());
			if (info.getSurplus() <= 0)
			{
				tv_num.setVisibility(View.GONE);
				tv_unit.setText("估清");
			} else if (info.getSurplus() > 0)
			{
				if (info.getOrderNum() > info.getSurplus())
				{
					ColorStateList redColors = ColorStateList.valueOf(0xfff04e39);
					String value = "仅剩" + info.getSurplus() + info.getUnit();
					SpannableStringBuilder spanBuilder = new SpannableStringBuilder(value);
					spanBuilder.setSpan(new TextAppearanceSpan(null, 0, DipPxConversion.sp2px(context, 12), redColors, null), 0, value.length(),
							Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
					tv_foodName.append(spanBuilder);
				}
				tv_num.setText(info.getOrderNum() + "");
				tv_num.setVisibility(View.VISIBLE);
				tv_unit.setText(info.getUnit());
				tv_num.setTag(info);
				tv_num.setTag(R.id.order_id, item.getOrderId());
				tv_num.setOnClickListener(onBaseClickListener);
			}
			tv_totalPrice.setText(SaleUtils.getSaleString(info.getPrice() * info.getOrderNum()));
			center_div.addView(viewItem);
			img_del.setTag(info);
			img_del.setTag(R.id.order_id, item.getOrderId());
			img_del.setOnClickListener(onBaseClickListener);
			if (!TextUtils.isEmpty(info.getTaste_types()))
			{
				tv_flavor_info.setVisibility(View.VISIBLE);
				parseFlavor(tv_flavor_info, info.getFlavor());
			} else
				tv_flavor_info.setVisibility(View.GONE);
			if (info.getGoods_type() == VodConstant.BUNDLE_TYPE)
			{
				lay_content_div.removeAllViews();
				List<FoodDetailInfo> retails = info.getFoodDetailInfoList();
				if (!CollectionUtils.isEmpty(retails))
				{
					iv_direction.setVisibility(View.VISIBLE);
					for (FoodDetailInfo foodDetailInfo : retails)
					{
						View fourView = LayoutInflater.from(context).inflate(R.layout.item_shop_cart_second_layout, null, false);
						BaseTextView tv_child_foodName = (BaseTextView) fourView.findViewById(R.id.tv_foodName);
						BaseTextView tv_num_unit = (BaseTextView) fourView.findViewById(R.id.tv_num_unit);
						BaseTextView tv_flavor_info_child = (BaseTextView) fourView.findViewById(R.id.tv_flavor_info);
						if (TextUtils.isEmpty(foodDetailInfo.getFlavor()))
						{
							tv_flavor_info_child.setVisibility(View.GONE);
						} else
						{
							tv_flavor_info_child.setText(foodDetailInfo.getFlavor());
							tv_flavor_info_child.setVisibility(View.VISIBLE);
						}
						tv_child_foodName.setText(foodDetailInfo.getName());
						tv_num_unit.setText(foodDetailInfo.getQuantity() + foodDetailInfo.getUnit() + "");
						lay_content_div.addView(fourView);
					}
				}
			} else
			{
				iv_direction.setVisibility(View.GONE);
			}
		}
		helper.setText(R.id.tv_total_price, SaleUtils.getSaleString(countCash(item.getOrderId())));
	}

	/**
	 * 解析口味
	 *
	 * @param view_flavor
	 * @param value
	 */

	private void parseFlavor(BaseTextView view_flavor, String value)
	{
		if (!TextUtils.isEmpty(value))
		{
			try
			{
				JSONArray array = new JSONArray(value);
				if (array.length() > 0)
				{
					String flavorValue = "";
					int count = array.length();
					for (int k = 0; k < count; k++)
					{

						if (k == count - 1)
							flavorValue += array.optString(k);
						else
							flavorValue += array.optString(k) + "；";
					}
					view_flavor.setText("口味：" + flavorValue);
				} else
				{
					view_flavor.setText("口味：标准");
				}
			} catch (JSONException e)
			{
				e.printStackTrace();
			}
		} else
		{
			view_flavor.setText("口味：标准");
		}
	}

	private OnBaseClickListener onBaseClickListener = new OnBaseClickListener()
	{
		@Override
		public void onBaseClick(final View v)
		{
			switch (v.getId())
			{
			case R.id.btn_cancel:
				new VodDialog.Builder(context).dialogEnum(VodDialog.DialogEnum.DOUBLE).btnNegativeText(R.string.cancel).btnNeutralText(R.string.sure)
						.cancelable(false).contentName("确认要把该微信点餐取消吗？").onCustomDialogListener(new VodDialog.Builder.OnCustomDialogListener()
						{
							@Override
							public void onOnlyCancelClick()
							{

							}

							@Override
							public void onOkClick()
							{
								weChatOrderData.requestWeChatOrderCancel(billId, new WeChatOrderData.IWeChatOrderInfoListener()
								{
									@Override
									public void onRequestSuccess(JSONObject jsonObject)
									{
										ToastUtils.showText(context, "取消成功");
										Intent intent = getIntent().putExtra(IntentKey.BILL_ID, billId);
										setResult(RESULT_OK, intent);
										finish();
									}
								});
							}

							@Override
							public void onCancelClick()
							{

							}
						}).build().show();
				break;
			case R.id.btn_sure:
				new VodDialog.Builder(context).dialogEnum(VodDialog.DialogEnum.DOUBLE).btnNegativeText(R.string.cancel).btnNeutralText(R.string.sure)
						.cancelable(false).contentName("确认要把该微信点餐下单吗？").onCustomDialogListener(new VodDialog.Builder.OnCustomDialogListener()
						{
							@Override
							public void onOnlyCancelClick()
							{

							}

							@Override
							public void onOkClick()
							{
								JSONArray jsonArray = ShoppingCartManager.getWeChatOrderGoodsArray(weChatInfoList);
								if (jsonArray != null && jsonArray.length() > 0)
								{
									Logger.e(jsonArray.toString());
									weChatOrderData.requestWeChatOrderSure(billId, jsonArray, new WeChatOrderData.IWeChatOrderInfoListener()
									{
										@Override
										public void onRequestSuccess(JSONObject jsonObject)
										{
											ToastUtils.showText(context, "下单成功");
											Intent intent = getIntent().putExtra(IntentKey.BILL_ID, billId);
											setResult(RESULT_OK, intent);
											finish();
										}
									});
								}
							}

							@Override
							public void onCancelClick()
							{

							}
						}).build().show();
				break;
			case R.id.img_del:
				new VodDialog.Builder(context).dialogEnum(VodDialog.DialogEnum.DOUBLE).btnNegativeText(R.string.cancel).btnNeutralText(R.string.sure)
						.cancelable(false).contentName("确认要删除该商品吗？").onCustomDialogListener(new VodDialog.Builder.OnCustomDialogListener()
						{
							@Override
							public void onOnlyCancelClick()
							{

							}

							@Override
							public void onOkClick()
							{
								String orderId = (String) v.getTag(R.id.order_id);
								GoodsInfo goodsInfo = (GoodsInfo) v.getTag();
								for (int i = 0; i < weChatInfoList.size(); i++)
								{
									WeChatInfo info = weChatInfoList.get(i);
									if (info.getOrderId().equals(orderId))
									{
										List<GoodsInfo> list = info.getGoodsInfoList();
										for (int j = 0; j < list.size(); j++)
										{
											GoodsInfo gInfo = list.get(j);
											if (goodsInfo.getGoodsId().equals(gInfo.getGoodsId()))
											{
												list.remove(gInfo);
												break;
											}
										}
										break;
									}
								}
								dataAdapter.notifyDataSetChanged();
								ToastUtils.showText(context, "删除成功");
							}

							@Override
							public void onCancelClick()
							{

							}
						}).build().show();
				break;
			case R.id.tv_num:
				GoodsInfo info = (GoodsInfo) v.getTag();
				String order_id = (String) v.getTag(R.id.order_id);
				String flavor = info.getTaste_types();
				JSONArray array = null;
				try
				{
					if (!TextUtils.isEmpty(flavor))
						array = new JSONArray(flavor);
				} catch (JSONException e)
				{
					e.printStackTrace();
				}
				if (array != null && array.length() > 0)
				{
					Intent intent = new Intent(context, WeChatOrderDialogActivity.class);
					intent.putExtra(IntentKey.GOODSINFO, info);
					intent.putExtra(IntentKey.FLAVOR, info.getFlavor());
					intent.putExtra(IntentKey.WECHAT_ORDER_ID, order_id);
					intent.putExtra(IntentKey.ACTIVITY_ENUM, ActivityDialogEnum.FLAVOR);
					startActivityForResult(intent, IntentCode.WECHATORDER_FLAOVR_REQUEST);
				} else
				{
					Intent intent = new Intent(context, WeChatOrderDialogActivity.class);
					intent.putExtra(IntentKey.GOODSINFO, info);
					intent.putExtra(IntentKey.WECHAT_ORDER_ID, order_id);
					intent.putExtra(IntentKey.ACTIVITY_ENUM, ActivityDialogEnum.DEFAULT);
					intent.putExtra(IntentKey.CUSTOM_DIALOG_LEFT_NAME, "数量");
					startActivityForResult(intent, IntentCode.WECHATORDER_GOODS_REQUEST);
				}
				break;
			default:
				break;
			}
		}
	};

	/**
	 * 计算小计
	 */
	private int countCash(String orderId)
	{
		int cashTotal = 0;
		for (WeChatInfo info : weChatInfoList)
		{
			if (info.getOrderId().equals(orderId))
			{
				List<GoodsInfo> infoList = info.getGoodsInfoList();
				for (GoodsInfo foodInfo : infoList)
				{
					cashTotal += foodInfo.getOrderNum() * foodInfo.getPrice();
				}
				info.setCashTotal(cashTotal);
				break;
			}
		}
		countCashTotal();
		return cashTotal;
	}

	/**
	 * 计算总计
	 */
	private void countCashTotal()
	{
		int cashTotal = 0;
		for (WeChatInfo info : weChatInfoList)
		{
			cashTotal += info.getCashTotal();
		}
		tv_cashTotal.setText(SaleUtils.getSaleString(cashTotal));
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == IntentCode.WECHATORDER_GOODS_REQUEST && resultCode == RESULT_OK && data != null)
		{
			String weChat_order_id = data.getStringExtra(IntentKey.WECHAT_ORDER_ID);
			GoodsInfo goodsInfo = (GoodsInfo) data.getSerializableExtra(IntentKey.GOODSINFO);
			for (WeChatInfo info : weChatInfoList)
			{
				if (weChat_order_id.equals(info.getOrderId()))
				{
					List<GoodsInfo> infoList = info.getGoodsInfoList();
					for (GoodsInfo foodInfo : infoList)
					{
						if (foodInfo.getGoodsId().equals(goodsInfo.getGoodsId()))
						{
							foodInfo.setOrderNum(goodsInfo.getOrderNum());
							break;
						}
					}
					break;
				}
			}
			dataAdapter.notifyDataSetChanged();
		} else if (requestCode == IntentCode.WECHATORDER_FLAOVR_REQUEST && resultCode == RESULT_OK && data != null)
		{
			String weChat_order_id = data.getStringExtra(IntentKey.WECHAT_ORDER_ID);
			GoodsInfo goodsInfo = (GoodsInfo) data.getSerializableExtra(IntentKey.GOODSINFO);
			List<GoodsInfo> goodsInfoList = (List<GoodsInfo>) data.getSerializableExtra(IntentKey.GOODS_LIST);
			for (WeChatInfo info : weChatInfoList)
			{
				if (weChat_order_id.equals(info.getOrderId()))
				{
					List<GoodsInfo> infoList = info.getGoodsInfoList();
					for (GoodsInfo foodInfo : infoList)
					{
						if (foodInfo.getGoodsId().equals(goodsInfo.getGoodsId()))
						{
							infoList.remove(foodInfo);
							infoList.addAll(goodsInfoList);
							break;
						}
					}
					break;
				}
			}
			dataAdapter.notifyDataSetChanged();
		}
	}

}
